using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;

namespace PhilWicklund.com.PollingWebPart
{
    public class PollingEditorPart : EditorPart
    {
        TextBox width;
        TextBox height;
        DropDownList chartType;
        
        protected override void CreateChildControls()
        {
            Controls.Add(new LiteralControl("Width (px):<br />"));
            width = new TextBox();
            this.Controls.Add(width);

            this.Controls.Add(new LiteralControl("<br /><br />"));

            Controls.Add(new LiteralControl("Height (px):<br />"));
            height = new TextBox();
            this.Controls.Add(height);

            this.Controls.Add(new LiteralControl("<br /><br />"));

            Controls.Add(new LiteralControl("Chart Type:<br />"));
            chartType = new DropDownList();
            
            chartType.Items.Add(SeriesChartType.Doughnut.ToString());
            chartType.Items.Add(SeriesChartType.Pie.ToString());
            this.Controls.Add(chartType);
        }

        public override void SyncChanges()
        {
            this.EnsureChildControls();
            PollingWebPart sourcePart = (PollingWebPart)this.WebPartToEdit;
            int width = sourcePart.ChartWidth;
            int height = sourcePart.ChartHeight;
            SeriesChartType type = sourcePart.ChartType;

            chartType.Items.FindByText(type.ToString()).Selected = true;
            this.width.Text = width.ToString();
            this.height.Text = height.ToString();
        }

        public override bool ApplyChanges()
        {
            this.EnsureChildControls();
            PollingWebPart targetPart = (PollingWebPart)this.WebPartToEdit;
            switch (chartType.SelectedItem.Text)
            {
                case "Doughnut": targetPart.ChartType = SeriesChartType.Doughnut; break;
                case "Pie": targetPart.ChartType = SeriesChartType.Pie; break;
            }

            try
            {
                targetPart.ChartWidth = int.Parse(width.Text);
            }
            catch { throw new Exception("ERROR: you must type only numbers in the Width text box."); }

            try
            {
                targetPart.ChartHeight = int.Parse(height.Text);
            }
            catch { throw new Exception("ERROR: you must type only numbers in the Height text box."); }

            return true;
        }
    }
}
